from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import Column
from sqlalchemy.orm.util import class_mapper
from sqlalchemy.orm.properties import ColumnProperty
from uuid import UUID
import uuid
import datetime

EntBase = declarative_base()

def toPrimitiveDict(self):
    '''
    Returns a dictionary with string keys and values - "primitive" types - int, string, etc
    '''
    result = {}
    for prop in class_mapper(self.__class__).iterate_properties:
        if isinstance(prop, ColumnProperty):
            key = prop.key
            value = self.__dict__[key]
            if isinstance(value, datetime.datetime):
                value = value.strftime("%Y-%m-%d %H:%M:%S")
            result[key] = value
        
#    for c in self.__table__.columns:
#        assert isinstance(c, Column)
#        result[c.name] = self[c.name]
    return result
    
EntBase.toPrimitiveDict = toPrimitiveDict

class EntityWithUUID(object):
    '''
    Entities which have a column 'id' which is UUID will inherit from this class to get come common functionalities.
    This class must be before EntBase in the inheritance order 
    '''
    def setUUID(self, uuidObj):
        assert isinstance(uuidObj, UUID)
        self.id = uuidObj.bytes
    
    def getUUID(self):
        return uuid.UUID(bytes=self.id)
    
    def toPrimitiveDict(self):
        '''
        Returns a dictionary with string keys and values - "primitive" types - int, string, etc
        '''
        result = EntBase.toPrimitiveDict(self)
        result['id'] = str(self.getUUID())
        return result